//
//  MapScreen.m
//  TowerDefence
//
//  Created by K3 on 5/25/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MapScreen.h"
#import "iCoreGUIController.h"

@implementation MapScreen

-(id)initWith:(iCoreGUIController *)_mainGUIController {
    self = [super initGameLayerWith:_mainGUIController];
    
    [self loadResource];
    
    self.isTouchEnabled = YES;
    
    return self;
}

-(void)loadResource {    
    recognizerTap = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)] autorelease];
    [[mainGUIController.mainDirector openGLView] addGestureRecognizer:recognizerTap];
    
    fullMapSprite = [[CCSprite alloc]initWithFile:IMAGE_MAP_SCREEN_FULL_MAP];
    fullMapSprite.anchorPoint = ccp(0, 0);
    fullMapSprite.position = ccp(0, 0);
    [self addChild:fullMapSprite z:0];
    
    //add back to previous screen button
    CCMenuItemImage *backPreviousScreenButton = [CCMenuItemImage itemFromNormalImage:IMAGE_OTHER_BACK_BUTTON_NORMAL selectedImage:IMAGE_OTHER_BACK_BUTTON_SELECTED target:self selector:@selector(backToPreviousScreen)];
    backPreviousMenu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [backPreviousMenu addChild:backPreviousScreenButton];
    backPreviousMenu.position = ccp(25, 25);
    [self addChild:backPreviousMenu];
    
    //add mute speaker menu icon
    //create 2 menu item image, this show speaker normal image fist
    CCMenuItemImage *speakerControl = [CCMenuItemImage itemFromNormalImage:IMAGE_OTHER_SPEAKER_NORMAL selectedImage:IMAGE_OTHER_SPEAKER_MUTE target:nil selector:nil];
    
    //this menuItemImage show speaker mute image fist
    CCMenuItemImage *speakerControlReverse = [CCMenuItemImage itemFromNormalImage:IMAGE_OTHER_SPEAKER_MUTE selectedImage:IMAGE_OTHER_SPEAKER_NORMAL target:nil selector:nil];
    
    //Create toogle to switch between speakerControl and speakerControlReverse
    CCMenuItemToggle *speakerMenuItem = nil;;
    if(mainGUIController.isMuteSound)
        speakerMenuItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(muteAllSound:) items:speakerControlReverse, speakerControl, nil];
    else
        speakerMenuItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(muteAllSound:) items:speakerControl, speakerControlReverse, nil];
    speakerMenuItem.scale = 1.25f;
    speakerMenu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [speakerMenu addChild:speakerMenuItem];
    speakerMenu.position = ccp(25, 300);
    [self addChild:speakerMenu z:100];
    
    //Draw flag on map background
    [self drawFlagOnMap];
    [self drawParticalOnMap];
    
    [mainGUIController playBackgroundSound:AUDIO_MAP_SCREEN_BACKGROUND withLoop:YES];
    [mainGUIController setBackgroundSoundVolume:0.25f];
    [mainGUIController preloadSoundEffectFile:AUDIO_BUTTON_CLICKED];
}

-(void)drawFlagOnMap {
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_RED_FLAG];
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_BLACK_FLAG];
    
    flagAniamtion = [mainGUIController loadAnimationFromCacheByName:@"redFlag" withCount:7 delay:0.15f];
    
    redFlag = [[CCSprite alloc]initWithSpriteFrameName:@"redFlag0.png"];
    redFlag.scale = 0.5f;
    [redFlag runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:flagAniamtion restoreOriginalFrame:NO]]];
    
    CCMenuItemSprite *map1MenuItem = [CCMenuItemSprite itemFromNormalSprite:redFlag selectedSprite:nil target:self selector:@selector(gotoMap:)];
    map1MenuItem.anchorPoint = ccp(0.5, 0);
    map1MenuItem.tag = TAG_MAP_SOUTHPORT;
    map1Menu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [map1Menu addChild:map1MenuItem];
    [fullMapSprite addChild:map1Menu z:1];
    map1Menu.position = ccp(fullMapSprite.contentSize.width/2 - 247, fullMapSprite.contentSize.height/2 - 182);
    
    redCircle1 = [[CCSprite alloc]initWithFile:IMAGE_RED_CIRCLE];
    redCircle1.position = ccp(fullMapSprite.contentSize.width/2 - 247 - 10, fullMapSprite.contentSize.height/2 - 182 +5);
    [fullMapSprite addChild:redCircle1 z:0];
    redCircle1.scale = 0.4;
    redCircle1.opacity = 70;
    [redCircle1 runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.75 scale:0.25], [CCScaleTo actionWithDuration:0.75 scale:0.4f], nil]]];
    
    constructTowerStickNote = [[CCSprite alloc]initWithFile:IMAGE_LEFT_STICK_NOTE];
    constructTowerStickNote.position = ccp(fullMapSprite.contentSize.width/2 - 247, fullMapSprite.contentSize.height/2 - 182 + 20);
    constructTowerStickNote.anchorPoint = ccp(0, 0);
    constructTowerStickNote.color = ccc3(255, 255, 196);
    constructTowerStickNote.scale = 0.75f;
    [constructTowerStickNote runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.5 scale:0.7], [CCScaleTo actionWithDuration:0.15 scale:0.75f], nil]]];
    CCLabelTTF *noteText = [CCLabelTTF labelWithString:@"Start here!!!" fontName:FONT_COMIC_BOOK fontSize:12];
    noteText.color = ccc3(33, 33, 33);
    noteText.anchorPoint = ccp(0.5f, 0.5f);
    noteText.position = ccp(constructTowerStickNote.contentSize.width/2 + 5, constructTowerStickNote.contentSize.height/2 + 5);
    [constructTowerStickNote addChild:noteText];
    [fullMapSprite addChild:constructTowerStickNote z:2 tag:TAG_CONSTRUCT_TOWER_STICK_NOTE_SPRITE];
    
    redFlag2 = [[CCSprite alloc]initWithSpriteFrameName:@"redFlag0.png"];
    redFlag2.scale = 0.5f;
    [redFlag2 runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:flagAniamtion restoreOriginalFrame:NO]]];
    
    CCMenuItemSprite *map2MenuItem = [CCMenuItemSprite itemFromNormalSprite:redFlag2 selectedSprite:nil target:self selector:@selector(gotoMap:)];
    map2MenuItem.anchorPoint = ccp(0.5, 0);
    map2MenuItem.tag = TAG_MAP_FARMLANDS;
    map2Menu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [map2Menu addChild:map2MenuItem];
    [fullMapSprite addChild:map2Menu z:1];
    map2Menu.position = ccp(fullMapSprite.contentSize.width/2 - 281, fullMapSprite.contentSize.height/2 - 98);
    
    redCircle2 = [[CCSprite alloc]initWithFile:IMAGE_RED_CIRCLE];
    redCircle2.position = ccp(fullMapSprite.contentSize.width/2 - 281 - 10, fullMapSprite.contentSize.height/2 - 98 +5);
    [fullMapSprite addChild:redCircle2 z:0];
    redCircle2.scale = 0.4;
    redCircle2.opacity = 70;
    [redCircle2 runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.75 scale:0.25], [CCScaleTo actionWithDuration:0.75 scale:0.4f], nil]]];
    
    redFlag4 = [[CCSprite alloc]initWithSpriteFrameName:@"redFlag0.png"];
    redFlag4.scale = 0.5f;
    [redFlag4 runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:flagAniamtion restoreOriginalFrame:NO]]];
    
    CCMenuItemSprite *map4MenuItem = [CCMenuItemSprite itemFromNormalSprite:redFlag4 selectedSprite:nil target:self selector:@selector(gotoMap:)];
    map4MenuItem.anchorPoint = ccp(0.5, 0);
    map4MenuItem.tag = TAG_MAP_TWINRIVERPASS;
    map4Menu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [map4Menu addChild:map4MenuItem];
    [fullMapSprite addChild:map4Menu z:1];
    map4Menu.position = ccp(fullMapSprite.contentSize.width/2 - 128, fullMapSprite.contentSize.height/2 - 124);
    
    redCircle4 = [[CCSprite alloc]initWithFile:IMAGE_RED_CIRCLE];
    redCircle4.position = ccp(fullMapSprite.contentSize.width/2 - 128 - 10, fullMapSprite.contentSize.height/2 - 124 +5);
    [fullMapSprite addChild:redCircle4 z:0];
    redCircle4.scale = 0.4;
    redCircle4.opacity = 70;
    [redCircle4 runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.75 scale:0.25], [CCScaleTo actionWithDuration:0.75 scale:0.4f], nil]]];
    
    redFlag3 = [[CCSprite alloc]initWithSpriteFrameName:@"redFlag0.png"];
    redFlag3.scale = 0.5f;
    [redFlag3 runAction:[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:flagAniamtion restoreOriginalFrame:NO]]];
    
    CCMenuItemSprite *map3MenuItem = [CCMenuItemSprite itemFromNormalSprite:redFlag3 selectedSprite:nil target:self selector:@selector(gotoMap:)];
    map3MenuItem.anchorPoint = ccp(0.5, 0);
    map3MenuItem.tag = TAG_MAP_PAGRAS;
    map3Menu = [[CCMenu alloc]initWithItems:nil vaList:nil];
    [map3Menu addChild:map3MenuItem];
    [fullMapSprite addChild:map3Menu z:1];
    map3Menu.position = ccp(fullMapSprite.contentSize.width/2 - 190, fullMapSprite.contentSize.height/2 - 90);
    
    redCircle3 = [[CCSprite alloc]initWithFile:IMAGE_RED_CIRCLE];
    redCircle3.position = ccp(fullMapSprite.contentSize.width/2 - 190 - 10, fullMapSprite.contentSize.height/2 - 90 +5);
    [fullMapSprite addChild:redCircle3 z:0];
    redCircle3.scale = 0.4;
    redCircle3.opacity = 70;
    [redCircle3 runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCScaleTo actionWithDuration:0.75 scale:0.25], [CCScaleTo actionWithDuration:0.75 scale:0.4f], nil]]];
}

-(void)drawParticalOnMap {
    [mainGUIController loadGraphicFromPlistFileToFrameCache:PLIST_RESOURCE_SILVER_LIGHT];
    
    //draw linghtning on des
    lightning = [[CCSprite alloc]initWithSpriteFrameName:@"silver_light_effect0.png"];
    NSMutableArray *lightAnimationFrame = [mainGUIController loadAnimationWithNumberOfFrames:9 withFrameName:@"silver_light_effect"];
    lightAniamtion = [[CCAnimation alloc]initWithFrames:lightAnimationFrame delay:0.075];
    
    lightning.anchorPoint = ccp(0.5, 0);
    //lightning.scale = 0.5f;
    lightning.position = ccp(fullMapSprite.contentSize.width/2 + 42, fullMapSprite.contentSize.height/2 + 190);
    [lightning runAction:[CCRepeat actionWithAction:[CCAnimate actionWithAnimation:lightAniamtion restoreOriginalFrame:NO] times:2]];
    
    [fullMapSprite addChild:lightning z:0];
    [self schedule:@selector(updateLightningPosition:) interval:2.0f];
    
    rainParticle = [[CCParticleRain alloc]init];
    rainParticle.texture = [[CCTextureCache sharedTextureCache] addImage:IMAGE_FIRE_ICON];
    rainParticle.position = ccp(240, 280);
    [self addChild:rainParticle];
}

-(void)updateLightningPosition:(ccTime)timeUpdate {
    float randomX = [self randomFloatBetween:20 and:60];
    float randomY = [self randomFloatBetween:170 and:210];
    lightning.position = ccp(fullMapSprite.contentSize.width/2 + randomX, fullMapSprite.contentSize.height/2 + randomY);
    
    //lightAniamtion = [mainGUIController loadAnimationFromCacheByName:@"silver_light_effect" withCount:9 delay:0.075];
    [lightning runAction:[CCRepeat actionWithAction:[CCAnimate actionWithAnimation:lightAniamtion restoreOriginalFrame:NO] times:2]];
}

- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
    float diff = bigNumber - smallNumber;
    return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}

-(void)gotoMap:(id)sender {    
    CCMenuItemSprite *menuItem = (CCMenuItemSprite *)sender;
    
    mainGUIController.currentMapRunning = menuItem.tag;
    //[mainGUIController startLoading:GAME_SCREEN_PLAY plistSpriteArr:nil];
    [mainGUIController runGameScreen:GAME_SCREEN_PLAY];
}

- (CGPoint)boundLayerPos:(CGPoint)newPos {    
    CGSize winSize = mainGUIController.mainDirector.winSize;
    CGPoint retval = newPos;
    retval.x = MIN(retval.x, 0);
  
    retval.x = MAX(retval.x, -fullMapSprite.contentSize.width+winSize.width); 
    //else
    //retval.x = MAX(retval.x, -winSize.width+winSize.width); 
    retval.y = MIN(0, retval.y);
  
    retval.y = MAX(-fullMapSprite.contentSize.height+winSize.height, retval.y);
    //else
    //retval.y = MAX(-winSize.height+winSize.height, retval.y);
    return retval;
}

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
    //just only move map sprite
    
    //NSLog(@"Gesture Clicked");
    if (recognizer.state == UIGestureRecognizerStateBegan) {    
        
        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [mainGUIController.mainDirector convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];                
        
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {    
        
        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = ccp(translation.x, -translation.y);
        CGPoint newPos = ccpAdd(fullMapSprite.position, translation);
        fullMapSprite.position = [self boundLayerPos:newPos];  
        [recognizer setTranslation:CGPointZero inView:recognizer.view];    
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        
        float scrollDuration = 0.2;
        CGPoint velocity = [recognizer velocityInView:recognizer.view];
        CGPoint newPos = ccpAdd(fullMapSprite.position, ccpMult(ccp(velocity.x, velocity.y * -1), scrollDuration));
        newPos = [self boundLayerPos:newPos];
        
        [fullMapSprite stopAllActions];
        CCMoveTo *moveTo = [CCMoveTo actionWithDuration:scrollDuration position:newPos];            
        [fullMapSprite runAction:[CCEaseOut actionWithAction:moveTo rate:1]];            
        
    }        
}

-(void)muteAllSound:(id)sender {
    [mainGUIController setMuteSoundPlayer:!mainGUIController.isMuteSound]; 
}

-(void)backToPreviousScreen {
    NSLog(@"back");
    [mainGUIController playEffect:AUDIO_BUTTON_CLICKED];
    [mainGUIController runGameScreen:GAME_SCREEN_MAIN_MENU];
}

-(void)dealloc {
    NSLog(@"Map screen dealloc");
    [mainGUIController unloadSoundEffectFile:AUDIO_BUTTON_CLICKED];
    
    [[mainGUIController.mainDirector openGLView] removeGestureRecognizer:recognizerTap];
    
    [mainGUIController removeAnimationInFrameCache:@"redFlag"];
    [lightAniamtion release];
    flagAniamtion = nil;
    lightAniamtion = nil;

    [backPreviousMenu release];
    [speakerMenu release];
    
    [redFlag release];
    [redCircle1 release];
    [redFlag2 release];
    [redCircle2 release];
    [redFlag3 release];
    [redCircle3 release];
    [redFlag4 release];
    [redCircle4 release];
    [rainParticle release];
    [fullMapSprite release];
    [lightning release];
    
    [map1Menu release];
    [map2Menu release];
    [map3Menu release];
    [map4Menu release];
    
    [self stopAllActions];
    [self removeAllChildrenWithCleanup:YES];
    
    //[mainGUIController cleanupFrameCacheSprite];
    
    [super dealloc];
}

@end
